package com.gzu.ltms.service.impl;

import com.gzu.ltms.entity.dto.AddressDTO;
import com.gzu.ltms.entity.dto.AddressUpdateDTO;
import com.gzu.ltms.holder.LoginUserContextHolder;
import com.gzu.ltms.response.Response;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.gzu.ltms.entity.Address;
import com.gzu.ltms.mapper.AddressMapper;
import com.gzu.ltms.service.AddressService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户常用地址表 服务层实现。
 *
 * @author mm
 * @since 2025-04-28
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    /**
     * 添加用户常用地址表
     * @param addressDTO 用户常用地址表
     * @return
     */
    @Override
    public Response<?> addAddress(AddressDTO addressDTO) {
        // 获取用户 ID
        Long userId = LoginUserContextHolder.getUserId();
        Address address = Address.builder()
                .userId(userId)
                .isDefault(false)
                .build();
        // 复制Bean属性
        BeanUtils.copyProperties(addressDTO, address);

        addressMapper.insert(address);
        return Response.success();
    }

    /**
     * 修改用户常用地址表
     * @param addressUpdateDTO
     * @return
     */
    @Override
    public Response<?> updateAddress(AddressUpdateDTO addressUpdateDTO) {
        Long userId = LoginUserContextHolder.getUserId();
        Address address = Address.builder()
                .userId(userId)
                .isDefault(false)
                .build();
        BeanUtils.copyProperties(addressUpdateDTO, address);
        addressMapper.update(address);
        return null;
    }

    /**
     * 获取用户常用地址表
     * @return
     */
    @Override
    public Response<List<Address>> getAllAddress() {
        // 获取用户 ID
        Long userId = LoginUserContextHolder.getUserId();
        List<Address> list = QueryChain.of(addressMapper)
                .eq(Address::getUserId, userId)
                .list();
        return Response.success(list);
    }
}
